<template>
  <el-upload
      :headers="headers"
      class="avatar-uploader"
      action="/api/user/common/upload"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
    <img v-if="avatar" :src="avatar" class="avatar">
    <img v-else-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-user-solid avatar-uploader-icon"></i>
  </el-upload>
</template>

<script lang="ts">
import {Vue, Component, Prop} from 'vue-property-decorator';

@Component({
  name: 'UploadImage',
})
export default class index extends Vue {
  @Prop() private avatar = ''  // 原先的图片
  private imageUrl = ''   // 新上传的图片
  private token = sessionStorage.getItem('authentication')
  headers = {authentication: this.token}

  handleAvatarSuccess(res) {
    this.imageUrl = res.data;
    //alert(this.imageUrl);
    this.$emit('imageAvatarSuccess', this.imageUrl)  // 子组件传值给父组件
  }



  beforeAvatarUpload(file) {
    const isJPG = file.type === 'image/jpeg';
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isJPG) {
      this.$message.error('上传头像图片只能是 JPG 格式!');
    }
    if (!isLt2M) {
      this.$message.error('上传头像图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
  }

}

</script>
<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
